#员工月工资统计服务类  flydragon
class Employees::UpdateService
  delegate :params, :session, to: :@view
  include HeiPisService

  #employee 员工
  def initialize(view,employee)
    @view = view
    @employee = employee
  end

  #执行方法 返回值
  def call

    success = true
    msg = "更新成功!"

    begin
      # 基本信息更新
      @employee.update!(employee_params)

      # 职务信息
      ActiveRecord::Base.transaction do
        
        save_employee_of_studio()
      end

      # 薪资信息
      ActiveRecord::Base.transaction do
        # 更新薪资
        add_salary()
      end

    rescue Exception => e
      success = false
      msg = "更新失败,提示信息为:#{e.message}"
      Rails.logger.info "更新失败,提示信息为:#{e.message}"
    end

    result = OpResult.new(success,msg)
    result.data = "/admin/employees/#{@employee.id}" if result.success
    result
  end


  private

  def employee_params
    params.require(:employee).permit(:name, :alias_name, :sex, :birthday, :weixin, :mobile, :emergency_contact, :emergency_mobile, :address, :remark , :avatar)
  end

  def employee_of_studio_params(info)
    data = {}
    [:position_id, :position_name,:department_id].each do |key|
       data[key.to_s] = info[key.to_s]
    end
    data
  end


  def save_employee_of_studio

    # delete employ_of _studio by employee_id
    EmployeeOfStudio.where(employee_id: @employee.id).destroy_all

    data_infos = params[:employee_of_studio]

    JSON.parse(data_infos).each do |info|

      # info = JSON.parse(info_str)
      studio_infos = info["studio_infos"]
      # p "info#{info.to_json}"
      studio_infos.each do |studio|
        age_group = info["age_group"]
        dance_type = info["dance_type"]
        teacher_level = info["teacher_level"]

        employee_of_studio = EmployeeOfStudio.new(employee_of_studio_params(info))
        employee_of_studio.employee_id = @employee.id
        employee_of_studio.employee_user_id = @employee.user_id
        employee_of_studio.studio_company_id = Studio.find(studio['studio_id']).company_id
        employee_of_studio.studio_id = studio['studio_id']
        employee_of_studio.save!

        if employee_of_studio.position_name=="导师"
          teacher = Teacher.new()
          teacher.name = @employee.name
          teacher.age_group = age_group
          teacher.dance_type = dance_type
          teacher.teacher_level = teacher_level if teacher_level
          teacher.employee_of_studio_id = employee_of_studio.id
          teacher.studio_id = employee_of_studio.studio_id
          teacher.company_id = employee_of_studio.studio_company_id
          teacher.save!
        end
      end
    end

  end

  
  # 添加薪资
  def add_salary

    str_to_float = lambda { |val| val.present? ? val.to_i : 0   }
    salary_base_param = {:employee_id => @employee.id,:employee_user_id => @employee.user_id}

    # delete salary for teacher
    # Salary.where("employee_id = :employee_id and salary_type like :salary_type",{:employee_id => @employee.id,:salary_type => "导师_%"}).destroy_all
    # 删除之前的员工薪资信息
    Salary.where("employee_id = :employee_id ",{:employee_id => @employee.id}).destroy_all
    # 添加导师薪资
    add_teacher_salary(salary_base_param,&str_to_float);

    # 添加福利补助
    add_welfare_salary(salary_base_param)

    # 添加基本工资
    add_base_salary(salary_base_param)

    
    salary_request_params = {:fuwuguwen_salary => "服务顾问_超出指标提成",
                    :chanpinzongjian_salary => "产品总监_超出指标提成",
                    :yunyingzongjian_salary => "运营总监_超出指标提成",
                    :shichangzongjian_salary => "市场总监_超出指标提成",
                    :shichangzhuanyuan_salary => "市场专员_超出指标提成"}

    Rails.logger.info "执行了#######################"                    
    
    salary_request_params.each do |key,name| 

      salary_info = JSON.parse(params[key])
      next if !salary_info["chaochu_info"].present?
      salary_info["chaochu_info"].each do |info|

        salary = Salary.new(salary_base_param)
        salary.salary_type = name
        salary.amount = str_to_float.call(info["scale"])
        salary.range_min = str_to_float.call(info["start"])
        salary.range_max = str_to_float.call(info["end"])
        salary.save!
      end
    end

  end

  

  # 添加导师薪资 参数结构为:eg
  # {
  #     "keshi_fee": "123",
  #     "ticheng_type": "阶段提成",
  #     "ticheng_info": [
  #         {
  #             "start": "0",
  #             "end": "12",
  #             "scale": "12"
  #         }
  #     ],
  #     "chaochu_info": [
  #         {
  #             "start": "0",
  #             "end": "12",
  #             "scale": "23"
  #         }
  #     ],
  #     "sijiao_scale": "23"
  # }
  def add_teacher_salary(salary_base_param,&str_to_float)

    # 获取导师薪资信息
    teacher_salary = JSON.parse(params[:teacher_salary])

    return if !teacher_salary.present? || EmployeeOfStudio.where(employee_id: @employee.id ,position_name: "导师").count==0

    # salary_base_param = {:employee_id => @employee.id,:employee_user_id => @employee.user_id}

    # 课时费
    if teacher_salary["keshi_fee"].present?
      salary = Salary.new(salary_base_param)
      salary.salary_type = "导师_课时费"
      salary.amount = str_to_float.call(teacher_salary["keshi_fee"])
      salary.save!
    end

    # 提成薪资
    ticheng_type = teacher_salary["ticheng_type"]
    if ticheng_type=="固定提成"
      salary = Salary.new(salary_base_param)
      salary.salary_type = "导师_固定提成"
      salary.amount = str_to_float.call(teacher_salary["ticheng_info"])
      salary.save!
      # 阶段提成
    elsif ticheng_type=="阶段提成"
      teacher_salary["ticheng_info"].each do |ticheng|
        salary = Salary.new(salary_base_param)
        salary.salary_type = "导师_阶段提成"
        salary.amount = str_to_float.call(ticheng["scale"])
        salary.range_min = str_to_float.call(ticheng["start"])
        salary.range_max = str_to_float.call(ticheng["end"])
        salary.save!
      end
    end

    # 导师_超出指标提成
    if teacher_salary["chaochu_info"].present?
      teacher_salary["chaochu_info"].each do |ticheng|
        salary = Salary.new(salary_base_param)
        salary.salary_type = "导师_超出指标提成"
        salary.amount = str_to_float.call(ticheng["scale"])
        salary.range_min = str_to_float.call(ticheng["start"])
        salary.range_max = str_to_float.call(ticheng["end"])
        salary.save!
      end
    end

    # 导师_私教提成
    if teacher_salary["sijiao_scale"].present?
      salary = Salary.new(salary_base_param)
      salary.salary_type = "导师_私教提成"
      salary.amount = str_to_float.call(teacher_salary["sijiao_scale"])
      salary.save!
    end

  end

  # 添加福利补助
  def add_welfare_salary(salary_base_param)

    # 获取导师薪资信息
    welfare_infos = JSON.parse(params[:welfare_salary])
    welfare_infos.each do |welfare_id|
      
      welfare = EmployeeWelfareConfiguration.find_by_id(welfare_id.to_i)

      next if !welfare.present?

      salary = Salary.new(salary_base_param)
      salary.salary_type = "福利补助_#{welfare.welfare_name}"
      salary.amount = welfare.amount
      salary.save!
    end
  end


  # 添加基本工资
  def add_base_salary(salary_base_param)

    # 获取导师薪资信息
    base_salary = params[:base_salary]
    return if !base_salary.present?

    salary = Salary.new(salary_base_param)
    salary.salary_type = "基本工资"
    salary.amount = base_salary.to_i
    salary.save!
  end



end
